package com.example.springboottx.controller;

import com.example.springboottx.bean.Publisher;
import com.example.springboottx.service.PublisherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class PublisherController {

    @Autowired
    private PublisherService publisherService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
    @GetMapping("/publisher/add/{name}")
    public Publisher addPublisher(@PathVariable("name") String name) throws InterruptedException {
        Publisher publisher = new Publisher();
        publisher.setName("测试出版社1");
        return publisherService.addPublisher(publisher.getName());
    }

    @GetMapping("/publisher/hash/{id}")
    public String findPublisherById(@PathVariable("id") Integer id) {
        Map<Object, Object> publisherMap = redisTemplate.opsForHash().entries("publisher." + id);
        if (publisherMap.isEmpty()) {
            Publisher publisher = publisherService.findPublisherById(id);
            publisherMap.put("name", publisher.getName());
            redisTemplate.opsForHash().putAll("publisher." + id, publisherMap);
            return "mysql: " + publisher;
        } else {
            return "redis: " + publisherMap.toString();
        }
    }

}
